package com.terrytian.springboottq.handler;

import com.terrytian.springboottq.annotation.Prevent;
import com.terrytian.springboottq.common.BusinessCode;
import com.terrytian.springboottq.common.BusinessException;
import com.terrytian.springboottq.util.CommonUtils;
import com.terrytian.springboottq.util.RedisUtil;
import com.terrytian.springboottq.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * @program: DevSpace
 * @ClassName DemoHandler
 * @description:
 * @author: tianqing
 * @create: 2022-11-26 19:33
 * @Version 1.0
 **/
public class DemoHandler implements PreventHandler {
    /**
     *
     * @param partKeyStr 存入redis的部分key
     * @param prevent @PPrevent
     * @param methodFullName 方法全名
     * @throws Exception
     */
    @Override
    public void handle(String partKeyStr, Prevent prevent, String methodFullName) throws Exception {
        String base64Str = CommonUtils.toBase64String(partKeyStr);

        long expire = Long.parseLong(prevent.time());

        //手动获取redis工具类
        RedisUtil redisUtil = (RedisUtil) SpringUtil.getBean("redisUtil");

        String resp = (String) redisUtil.get(methodFullName + base64Str);
        if (StringUtils.isEmpty(resp)) {
            redisUtil.set(methodFullName + base64Str, partKeyStr, expire);
        } else {
            String message = !StringUtils.isEmpty(prevent.message()) ? prevent.message() :
                    expire + "秒内不允许重复请求！";
            throw new BusinessException(BusinessCode.EXCEPTION, message);
        }

    }
}